require "Project/Engine/Classlite"

EventSet = classlite();

function EventSet:ctor()
	self._listeners = {};
end

function EventSet:addListener(type, listener, priority)
	if listener == nil then return end
	if priority == nil then priority = 0 end
	
	local record = self._listeners[type];
	if record == nil then
		self._listeners[type] = { listener=listener, priority=priority};
		return;
	end
	
	local prev = nil;
	while record ~= nil do
		local t=record.listener;
		local t1=listener;
		if t == t1 then
			return
		end
		if record.priority < priority then break end
		
		prev 	= record;
		record 	= record.next;
	end
	
	local data = { listener=listener, priority=priority, next=record };
	if prev == nil then self._listeners[type] = data;
	else prev.next = data; end
end

function EventSet:removeListener(type, listener)
	local data = self._listeners[type];
	if data == nil then return end
	if listener == nil then self._listeners[type] = nil; return end
	
	local prev;
	while data ~= nil do
		if data.listener == listener then
			if prev == nil then
				if data.next == nil then self._listeners[type] = nil;
				else self._listeners[type] = data.next; end
			else
				prev.next = data.next;
			end
			data.listener = nil;
			data.next = nil;
			return;
		end
		
		prev = data;
		data = data.next;
	end
end

function EventSet:hasListener(type, listener)
	local data = self._listeners[type];
	if data == nil then return false end
	if listener == nil then return true end
	
	while data ~= nil do
		if data.listener == listener then return true end
		data = data.next;
	end
	
	return false;
end

function EventSet:dispatchEvent(type, params)
	local record = self._listeners[type];
	if record == nil then return false end
	while record ~= nil do
		record.listener(type, self, params);
		record = record.next;
	end
	return true;
end

function EventSet:removeAllListeners()
	self._listeners = {}
end
